<?php

namespace App\Services;

use App\Models\Crm_Member;
use App\Models\Crm_Member_Auth;
use App\Models\Crm_Member_Photo;
use App\Traits\External;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Throwable;

class ExamineService
{
    public function baseInfo($params)
    {
        $dataNum = Crm_Member::where('agencyid',$params['aid'])
            ->where('status','wait')
            ->Nodel()
            ->count();
        $avatarNum = Crm_Member::whereHas('hasOneMemberAuth',function ($query){
            $query->where('aflag','wait');
        })->where('agencyid',$params['aid'])
            ->Nodel()
            ->count();
        $photoNum = Crm_Member_Photo::where('agencyid',$params['aid'])
            ->where('status','wait')
            ->Nodel()
            ->count();
        $introNum = Crm_Member::whereHas('hasOneMemberAuth',function ($query){
            $query->where('iflag','wait');
        })->where('agencyid',$params['aid'])
            ->Nodel()
            ->count();

        $list['dataNum'] = $dataNum;
        $list['avatarNum'] = $avatarNum;
        $list['photoNum'] = $photoNum;
        $list['introNum'] = $introNum;
        return $list;
    }

    public function checkData($params)
    {
        $field = config('fields.checkFields');
        $result = Crm_Member::getFilter($params)->select($field)
            ->Nodel()
            ->paginate($params['pageSize']);
        foreach ($result as $key => $value){
            $result[$key]['sibling'] = $value->hasOneMemberAnnex->sibling;
            $result[$key]['siblingText'] = $value->hasOneMemberAnnex->siblingText;
        }
        $result->data = $result->makeHidden(['hasOneMemberAnnex']);
        $list['total'] = $result->total();
        $list['list'] = $result->items();

        return $list;
    }

    public function dataStatusUpdate($params)
    {
        $ids = explode(',',$params['ids']);
        try {
            // 开始数据库事务
            DB::beginTransaction();

            foreach ($ids as $id) {
                $res = Crm_Member::find($id);
                $res->status = $params['status'];
                $res->reason = $params['status'] ?: '';
                if(!$res->save()){
                    throw new \Exception("更新Crm_Member资料状态失败".$id);
                }
            }

            DB::commit();
            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function checkAvatar($params)
    {
        $result = Crm_Member_Auth::getFilter($params)->whereHas('hasOneMember',function ($query) {
            $query->whereNotNull('avatar')->Nodel();
        })->paginate($params['pageSize']);
        $arr = [];
        foreach ($result as $key => $value){
            $arr[$key]['id'] = $value->id;
            $arr[$key]['mid'] = $value->mid;
            $arr[$key]['sn'] = $value->hasOneMember->sn;
            $arr[$key]['avatar'] = $value->hasOneMember->avatar;
            $arr[$key]['gender'] = $value->hasOneMember->gender;
            $arr[$key]['genderText'] = $value->hasOneMember->genderText;
            $arr[$key]['username'] = $value->hasOneMember->username;
            $arr[$key]['mobile'] = $value->hasOneMember->mobile;
            $arr[$key]['aflag'] = $value->aflag;
            $arr[$key]['aflagText'] = Crm_Member_Auth::$aflag[$value->aflag];
        }
        $list['total'] = $result->total();
        $list['list'] = $arr;

        return $list;
    }

    public function avatarStatusUpdate($params)
    {
        $ids = explode(',',$params['ids']);
        try {
            // 开始数据库事务
            DB::beginTransaction();

            foreach ($ids as $id) {
                $res = Crm_Member_Auth::find($id);
                $res->aflag = $params['aflag'];
                if(!$res->save()){
                    throw new \Exception("更新Crm_Member_Auth头像状态失败".$id);
                }
            }

            DB::commit();
            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function checkPhoto($params)
    {
        $result = Crm_Member_Photo::getFilter($params)->whereHas('hasOneMember',function ($query) {
            $query->Nodel();
        })->Nodel()->paginate($params['pageSize']);
        $arr = [];
        foreach ($result as $key => $value){
            $arr[$key]['id'] = $value->id;
            $arr[$key]['mid'] = $value->mid;
            $arr[$key]['sn'] = $value->hasOneMember->sn;
            $arr[$key]['age'] = $value->hasOneMember->age ?: '无';
            $arr[$key]['gender'] = $value->hasOneMember->gender;
            $arr[$key]['genderText'] = $value->hasOneMember->genderText;
            $arr[$key]['username'] = $value->hasOneMember->username ?: '无';
            $arr[$key]['url'] = $value->url;
            $arr[$key]['status'] = $value->status;
            $arr[$key]['statusText'] = Crm_Member_Photo::$status[$value->status];
            $arr[$key]['created_at'] = Carbon::parse($value->created_at)->toDateTimeString();
        }
        $list['total'] = $result->total();
        $list['list'] = $arr;

        return $list;
    }

    public function photoStatusUpdate($params)
    {
        $ids = explode(',',$params['ids']);
        try {
            // 开始数据库事务
            DB::beginTransaction();

            foreach ($ids as $id) {
                $res = Crm_Member_Photo::find($id);
                $res->status = $params['status'];
                if(!$res->save()){
                    throw new \Exception("更新Crm_Member_Photo相册状态失败".$id);
                }
            }

            DB::commit();
            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function checkIntro($params)
    {
        $result = Crm_Member_Auth::getFilter($params)->whereHas('hasOneMember',function ($query) {
            $query->whereNotNull('intro')->Nodel();
        })->paginate($params['pageSize']);
        $arr = [];
        foreach ($result as $key => $value){
            $arr[$key]['id'] = $value->id;
            $arr[$key]['mid'] = $value->mid;
            $arr[$key]['sn'] = $value->hasOneMember->sn;
            $arr[$key]['intro'] = $value->hasOneMember->intro;
            $arr[$key]['gender'] = $value->hasOneMember->gender;
            $arr[$key]['genderText'] = $value->hasOneMember->genderText;
            $arr[$key]['username'] = $value->hasOneMember->username;
            $arr[$key]['mobile'] = $value->hasOneMember->mobile;
            $arr[$key]['iflag'] = $value->iflag;
            $arr[$key]['iflagText'] = Crm_Member_Auth::$iflag[$value->iflag];
        }
        $list['total'] = $result->total();
        $list['list'] = $arr;

        return $list;
    }

    public function infoStatusUpdate($params)
    {
        $ids = explode(',',$params['ids']);
        try {
            // 开始数据库事务
            DB::beginTransaction();

            foreach ($ids as $id) {
                $res = Crm_Member_Auth::find($id);
                $res->iflag = $params['iflag'];
                if(!$res->save()){
                    throw new \Exception("更新Crm_Member_Auth自我介绍状态失败".$id);
                }
            }

            DB::commit();
            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function realAuthList($params)
    {
        $result = Crm_Member_Auth::getFilter($params)->select(['id','mid','idcard','paperimg1','paperimg2','paperimg3','flag'])
            ->whereHas('hasOneMember',function ($query) {
            $query->Nodel();
        })->whereNotNull('idcard')
            ->whereNotNull('paperimg1')
            ->whereNotNull('paperimg2')
            ->paginate($params['pageSize']);
        $list['total'] = $result->total();
        $result = External::optionResult($result,1);
        $list['list'] = $result;
        return $list;
    }

    public function realAuthStatusUpdate($params)
    {
        $ids = explode(',',$params['ids']);
        try {
            // 开始数据库事务
            DB::beginTransaction();

            foreach ($ids as $id) {
                $res = Crm_Member_Auth::find($id);
                $res->flag = $params['flag'];
                if(!$res->save()){
                    throw new \Exception("更新Crm_Member_Auth实名认证状态失败".$id);
                }
            }

            DB::commit();
            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function eduAuthList($params)
    {
        $result = Crm_Member_Auth::getFilter($params)->select(['id','mid','eduimg','eflag'])
            ->whereHas('hasOneMember',function ($query) {
                $query->Nodel();
            })->whereNotNull('eduimg')
            ->paginate($params['pageSize']);
        $list['total'] = $result->total();
        $result = External::optionResult($result,1);
        $list['list'] = $result;
        return $list;
    }

    public function eduAuthStatusUpdate($params)
    {
        $ids = explode(',',$params['ids']);
        try {
            // 开始数据库事务
            DB::beginTransaction();

            foreach ($ids as $id) {
                $res = Crm_Member_Auth::find($id);
                $res->eflag = $params['eflag'];
                if(!$res->save()){
                    throw new \Exception("更新Crm_Member_Auth学历认证状态失败".$id);
                }
            }

            DB::commit();
            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function houseAuthList($params)
    {
        $result = Crm_Member_Auth::getFilter($params)->select(['id','mid','houseimg','hflag'])
            ->whereHas('hasOneMember',function ($query) {
                $query->Nodel();
            })->whereNotNull('houseimg')
            ->paginate($params['pageSize']);
        $list['total'] = $result->total();
        $result = External::optionResult($result,1);
        $list['list'] = $result;
        return $list;
    }

    public function houseAuthStatusUpdate($params)
    {
        $ids = explode(',',$params['ids']);
        try {
            // 开始数据库事务
            DB::beginTransaction();

            foreach ($ids as $id) {
                $res = Crm_Member_Auth::find($id);
                $res->eflag = $params['hflag'];
                if(!$res->save()){
                    throw new \Exception("更新Crm_Member_Auth房产认证状态失败".$id);
                }
            }

            DB::commit();
            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function carAuthList($params)
    {
        $result = Crm_Member_Auth::getFilter($params)->select(['id','mid','carimg','cflag'])
            ->whereHas('hasOneMember',function ($query) {
                $query->Nodel();
            })->whereNotNull('carimg')
            ->paginate($params['pageSize']);
        $list['total'] = $result->total();
        $result = External::optionResult($result,1);
        $list['list'] = $result;
        return $list;
    }

    public function carAuthStatusUpdate($params)
    {
        $ids = explode(',',$params['ids']);
        try {
            // 开始数据库事务
            DB::beginTransaction();

            foreach ($ids as $id) {
                $res = Crm_Member_Auth::find($id);
                $res->eflag = $params['cflag'];
                if(!$res->save()){
                    throw new \Exception("更新Crm_Member_Auth车子认证状态失败".$id);
                }
            }

            DB::commit();
            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function singleAuthList($params)
    {
        $result = Crm_Member_Auth::getFilter($params)->select(['id','mid','singleimg','sflag'])
            ->whereHas('hasOneMember',function ($query) {
                $query->Nodel();
            })->whereNotNull('singleimg')
            ->paginate($params['pageSize']);
        $list['total'] = $result->total();
        $result = External::optionResult($result,1);
        $list['list'] = $result;
        return $list;
    }

    public function singleAuthStatusUpdate($params)
    {
        $ids = explode(',',$params['ids']);
        try {
            // 开始数据库事务
            DB::beginTransaction();

            foreach ($ids as $id) {
                $res = Crm_Member_Auth::find($id);
                $res->eflag = $params['sflag'];
                if(!$res->save()){
                    throw new \Exception("更新Crm_Member_Auth单身认证状态失败".$id);
                }
            }

            DB::commit();
            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }
}
